package com.handpay.nocardpay.baselibrary.main.mine;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.download.view.activity.DownloadApkActivity;
import com.handpay.nocardpay.baselibrary.guide.view.IVersionView;
import com.handpay.nocardpay.baselibrary.main.all.view.fragment.AllFragment;
import com.handpay.nocardpay.baselibrary.main.home.view.fragment.HomeFragment;
import com.handpay.nocardpay.baselibrary.main.mine.view.fragment.MineFragment;
import com.handpay.nocardpay.baselibrary.notification.push.NoticeListener;
import com.handpay.nocardpay.baselibrary.notification.push.NoticePushFactory;
import com.handpay.nocardpay.baselibrary.notification.service.NoticeService;
import com.handpay.nocardpay.baselibrary.smartrepayment.SmartRePayFragment;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.NoCardPayConstant;
import com.handpay.nocardpay.baselibrary.utils.PreferenceManager;
import com.handpay.nocardpay.baselibrary.widget.BottomBar;
import com.handpay.nocardpay.baselibrary.widget.BottomBarTab;
import com.handpay.nocardpay.baselibrary.widget.DisplayUtil;
import com.yuyh.library.EasyGuide;
import com.yuyh.library.bean.HighlightArea;
import com.yuyh.library.support.HShape;
import com.yuyh.library.support.OnStateChangedListener;

import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by sxshi on 2017/8/9.
 */

public class MainFragment extends BaseFragment implements IVersionView, NoticeListener {
//    private VersionPresenterImpl mVersionPresenter;
//    private HashMap<String, Object> paramers;
    public static final int HOME = 0;
    public static final int ALL =1;
    public static final int MINE = 2;

    private SupportFragment[] mFragments = new SupportFragment[3];

    private BottomBar mBottomBar;
    private BottomBarTab  homeBottomBarTab,allBottomBarTab , mineBottomBarTab;

    private RelativeLayout rl_root;
    private ImageView smartView;
    //智能还款引导页
    private EasyGuide easyGuide;

    public static MainFragment newInstance() {
        Bundle args = new Bundle();
        MainFragment fragment = new MainFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_main;
    }

    @Override
    public void initView(View view) {
        rl_root = (RelativeLayout) view.findViewById(R.id.rl_root);
        mBottomBar = (BottomBar) view.findViewById(R.id.bottomBar);
        smartView = new ImageView(_mActivity);
        homeBottomBarTab = new BottomBarTab(_mActivity, R.drawable.main_tab_icon_all, getString(R.string.home));
        allBottomBarTab = new BottomBarTab(_mActivity, R.drawable.main_tab_icon_home, getString(R.string.mine));
        mineBottomBarTab = new BottomBarTab(_mActivity, R.drawable.main_tab_icon_mine, getString(R.string.mine));
        mBottomBar.addItem(homeBottomBarTab).addItem(allBottomBarTab).addItem(mineBottomBarTab);
        startNoticeService();
        NoticePushFactory.with().registerNoticeListener(this);
    }

    //登入后拉起通知服务
    private void startNoticeService() {
        Intent service = new Intent(_mActivity, NoticeService.class);
        _mActivity.startService(service);
    }

    @Override
    public void initListener() {
        mBottomBar.setOnTabSelectedListener(new BottomBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {
                showHideFragment(mFragments[position], mFragments[prePosition]);
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        HomeFragment homeFragment = findFragment(HomeFragment.class);
        if (homeFragment == null) {
            mFragments[HOME] = HomeFragment.newInstance();
            mFragments[ALL]  = AllFragment.newInstance();
            mFragments[MINE] = MineFragment.newInstance();

            loadMultipleRootFragment(R.id.fl_tab_container, HOME,  mFragments[HOME],mFragments[ALL], mFragments[MINE]);
        } else {
            mFragments[HOME] = homeFragment;
            mFragments[ALL]  = findFragment(AllFragment.class);
            mFragments[MINE] = findFragment(MineFragment.class);
        }


//        mVersionPresenter = new VersionPresenterImpl(this, _mActivity);
//        paramers = new HashMap<>();
//        paramers.put(BaseProtocolKey.VERSION, ClientEngine.getInstance().VERSION);
//        paramers.put(BaseProtocolKey.PLATFORM, ClientEngine.getInstance().MOBILE_TYPE);
//        paramers.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);

    }

    @Override
    public void onResume() {
        super.onResume();
//        mVersionPresenter.checkVersion(paramers, false);
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
//        if (requestCode == QualificationStatuInfoFragment.QualificationStatuInfoFragmentRequestCode){
//
//        }
    }

    @Override
    public void lastVersion() {

    }

    @Override
    public void noRemindVersion(String title, String message, final String url, final String version) {

    }

    @Override
    public void forcedUpdateApk(String title, String message, final String url) {
        DialogUtils.showAlertDialog(_mActivity, title, message, false, getResources().getString(R.string.immediately_update), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                goToDownloadActivity(_mActivity, url);
            }
        });
    }

    @Override
    public void normalUpdateApk(String title, String message, final String url, final String version) {
        DialogUtils.showAlertDialog(_mActivity, title, message, getResources().getString(R.string.immediately_update), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                goToDownloadActivity(_mActivity, url);
            }
        }, getResources().getString(R.string.not_update), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                lastVersion();
                PreferenceManager.getInstance(_mActivity.getApplicationContext()).putBoolean(NoCardPayConstant.IS_NOT_REMIND, false);
            }
        }, getResources().getString(R.string.no_longer_remind), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int arg1) {
                dialog.dismiss();
                PreferenceManager.getInstance(_mActivity.getApplicationContext()).putBoolean(NoCardPayConstant.IS_NOT_REMIND, true);
                PreferenceManager.getInstance(_mActivity.getApplicationContext()).putString(NoCardPayConstant.NOT_REMIND_VERSION, version);
                lastVersion();
            }
        });
    }

    protected void goToDownloadActivity(Activity activity, String url) {
        Intent intent = new Intent(activity, DownloadApkActivity.class);
        intent.putExtra(DownloadApkActivity.DOWNLOAD_APK_URL, url);
        activity.startActivity(intent);
    }

    @Override
    public void detectedNotice(boolean flag) {
        mineBottomBarTab.setNewMsg(flag);
    }





//    /**
//     * 添加代还信用卡按钮
//     */
//    public void addSmartView() {
//        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
//        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
//        smartView.setBackgroundResource(R.drawable.main_tab_icon_all);
//        smartView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                start(SmartRePayFragment.newInstance());
//            }
//        });
//        layoutParams.setMargins(0, 0, 0, 30);
//        rl_root.removeView(smartView);
//        rl_root.addView(smartView, layoutParams);
//        //判断是否要添加引导
//        if (PreferenceManager.getInstance(_mActivity).getBoolean(NoCardPayConstant.SMART_PAY_TIPS_SHOW_MAIN_VIEW, true)) {
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    OnStateChangedListener listener = new OnStateChangedListener() {
//                        @Override
//                        public void onShow() {
//                        }
//                        @Override
//                        public void onDismiss() {
//                            PreferenceManager.getInstance(_mActivity).putBoolean(NoCardPayConstant.SMART_PAY_TIPS_SHOW_MAIN_VIEW, false);
//                        }
//                    };
//                    showGuideTips(smartView,listener);
//                }
//            },200);
//        }
//    }

    private View createTipsView() {
        View view = LayoutInflater.from(_mActivity).inflate(R.layout.layout_tips_view, null);
        return view;
    }

    private void showGuideTips(View view,OnStateChangedListener listener) {
        int[] loc = new int[2];
        view.getLocationOnScreen(loc);
        int y = (DisplayUtil.getScreenHeight(_mActivity) - loc[1]) * -1;
        View tipsView = createTipsView();
        if (easyGuide != null && easyGuide.isShowing())
            easyGuide.dismiss();
        HighlightArea area = new HighlightArea(view, HShape.OVAL) {
            @Override
            public RectF getRectF() {
                RectF rectF = new RectF();
                if (mHightlightView != null) {
                    int[] location = new int[2];
                    mHightlightView.getLocationOnScreen(location);
                    rectF.left = location[0] - 30;
                    rectF.top = location[1] - 30;
                    rectF.right = location[0] + mHightlightView.getWidth() + 30;
                    rectF.bottom = location[1] + mHightlightView.getHeight() + 30;
                }
                return rectF;
            }
        };
        easyGuide = new EasyGuide.Builder(_mActivity)
                // 增加View高亮区域，可同时显示多个
                .addHightLightArea(area)
                // 复杂的提示布局，建议通过此方法，较容易控制
                .addView(tipsView, 0, y, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
                // 若点击作用在高亮区域，是否执行高亮区域的点击事件
//                .performViewClick(true)
                .build();

        easyGuide.setOnStateChangedListener(listener);

        easyGuide.show();
    }

    /**
     * 刪除代还引用卡按钮
     */
    public void removeView() {
        rl_root.removeView(smartView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NoticePushFactory.with().unregisterNoticeListener(this);
    }
}
